const app = getApp();

/*  resolve对象，用then()方法处理，code为200代表成功,payload为房间ID
 *  功能用法，例:
 *  saveOrUpdateRoomInfo().then(function(res) {
 *      //在里面处理数据
 *      console.log(res);
 *  });
 *  cloudLogin()应该放在onLoad()函数里
 */

/**
 * 设备类型枚举
 */
var DeviceType = {
    CCT: 'CCT',
    RGB: 'RGB',
    PURE: 'PURE',
    OLD: 'OLD',
};
var ip = "cnwifidevsdk.magichue.net"
// var ip = "luoke365.wicp.net"
// var ip = "192.168.1.11"
// var ip = "localhost"
var port = '8989'

/**
 * 登陆,更新app.js下的payload
 * @returns code, payload
 */
export async function cloudLogin() {
    return new Promise(function (resolve, reject) {
        wx.login({
            success(res) {
                wx.request({
                    url: 'https://' + ip + ':' + port + '/weChat/SignIn?code=' + res.code,
                    method: 'GET',
                    data: {
                        code: res.code
                    },
                    success: res => {
                        // console.log(res)
                        app.globalData.payload = res.data.payload
                        console.log("login success : ", app.globalData.payload)
                        resolve()
                    }
                })
            }
        })
    })
}

/**
 * 添加或更新房间信息，如果是更新房间信息请带上房间ID, 新添加的房间不需要
 * @param {房间的名称} roomName 
 * @param {房间的ID} roomId 
 * @returns resolve对象: code, payload{房间ID}
 */
export async function saveOrUpdateRoomInfo(roomName, roomId) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/room/saveOrUpdateRoomInfo',
            method: "POST",
            header: {
                'Content-Type': 'application/json',
                'tate': app.globalData.payload
            },
            data: {
                "roomName": roomName,
                "roomId": roomId,
            },
            success(res) {
                resolve(res.data)
            },
        })
    })
}

/**
 * 获取房间列表
 * @returns resolve对象: code, payload{房间ID, 房间名称}
 */
export async function roomListGet() {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/room/roomListGet',
            method: "GET",
            header: {
                'tate': app.globalData.payload
            },
            success(res) {
                app.globalData.roomList = res.data.payload
                resolve(res.data.payload)
            },
        })
    })
}

/**
 * 获取单个房间
 * @param {房间的ID} roomId 
 * @returns resolve对象: code, payload{房间ID, 房间名称}
 */
export async function roomGet(roomId) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/room/roomGet?roomId=' + roomId,
            method: "GET",
            header: {
                'tate': app.globalData.payload
            },
            success(res) {
                resolve(res.data)
            },
        })
    })
}

/**
 * 删除房间
 * @param {房间的ID} roomId 
 * @returns resolve对象: code, payload(true)
 */
export async function roomDelete(roomId) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/room/roomDelete?roomId=' + roomId,
            method: "GET",
            header: {
                'tate': app.globalData.payload
            },
            success(res) {
                resolve(res)
            },
        })
    })
}

/**
 * 添加或更新设备信息，如果是更新设备信息请带上设备ID, 新添加的设备不需要
 * 其余参数可不填，默认deviceType为CCT，默认deviceCct为0，默认deviceBrightness为0
 * 所有设备类型已经枚举在文件顶部
 * @param {房间的ID} roomId 
 * @param {设备的名称} deviceName 
 * @param {设备的类型} deviceType 
 * @param {设备的色温} deviceCct 
 * @param {设备的亮度} deviceBrightness 
 * @param {设备的ID} deviceId 
 * @returns resolve对象: code, payload{设备ID}
 */
export async function saveOrUpdateDevice(roomId, deviceName, deviceType = DeviceType.CCT, deviceCct = 0, deviceBrightness = 0, deviceId) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/device/saveOrUpdateDevice',
            method: "POST",
            header: {
                'Content-Type': 'application/json',
                'tate': app.globalData.payload
            },
            data: {
                "roomId": roomId,
                "deviceName": deviceName,
                "deviceCct": deviceCct,
                "deviceBrightness": deviceBrightness,
                "deviceType": deviceType,
                "deviceId": deviceId,
            },
            success(res) {
                resolve(res.data)
            },
        })
    })
}


/**
 * 获取某房间下的设备列表
 * @param {房间的ID} roomId 
 * @returns resolve对象: code, payload{设备的亮度, 设备的色温, 设备名称, macAddress, 房间ID}
 */
export async function deviceListGet(roomId) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/device/deviceListGet?roomId=' + roomId,
            method: "GET",
            header: {
                'tate': app.globalData.payload
            },
            success(res) {
                resolve(res.data)
            },
        })
    })
}

/**
 * 获取设备信息
 * @param {房间的ID} device 
 * @returns resolve对象: code, payload{设备的亮度, 设备的色温, 设备名称, macAddress, 房间ID}
 */
export async function deviceGet(device) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/device/deviceGet?deviceId=' + device,
            method: "GET",
            header: {
                'tate': app.globalData.payload
            },
            success(res) {
                resolve(res.data)
            },
        })
    })
}

/**
 * 删除设备信息
 * @param {房间的ID} device 
 * @returns resolve对象: code, payload(true)
 */
export async function deviceDelete(device) {
    return new Promise(function (resolve, reject) {
        wx.request({
            url: 'https://' + ip + ':' + port + '/device/deviceDelete?deviceId=' + device,
            method: "GET",
            header: {
                'tate': app.globalData.payload
            },
            success(res) {
                resolve(res.data)
            },
        })
    })
}

/**
 * 更新[ 房间和设备 ]数组
 * @param {Array} roomList 房间列表
 */
export async function updateRoomDevList(roomList) {
    // var that = this
    var list = []
    var tmpRoom = { roomId: 0, roomName: '', roomMac: 0, roomStatus: 0, devList: [] }
    var tmpDev = { roomId: 0, roomMac: 0, devId: 0, devName: '', devMac: 0, devType: '', devBrightness: 0, devCW: 0, }
    for (let index = 0; index < roomList.length; index++) {
        var saveAllLight = []
        tmpRoom.roomId = roomList[index].roomId
        tmpRoom.roomName = roomList[index].roomName
        tmpRoom.roomMac = roomList[index].address
        await deviceListGet(roomList[index].roomId).then(function (res) {
            // console.log(res.payload)
            var devices = res.payload

            // push tmpRoom.devList[]
            for (let j = 0; j < devices.length; j++) {
                var br = JSON.parse(devices[j].deviceBrightness)
                var cw = JSON.parse(devices[j].deviceCct)
                saveAllLight.push(br)

                tmpDev.roomId = devices[j].roomId
                tmpDev.roomMac = roomList[index].address
                tmpDev.devId = devices[j].deviceId
                tmpDev.devName = devices[j].deviceName
                tmpDev.devMac = devices[j].macAddress
                tmpDev.devType = devices[j].deviceType
                tmpDev.devBrightness = br
                tmpDev.devCW = cw

                tmpRoom.devList.push(tmpDev)
                // 复位
                tmpDev = { roomId: 0, roomMac: 0, devId: 0, devName: '', devMac: 0, devType: '', devBrightness: 0, devCW: 0, }
            }
        })
        // room all dev status
        if (saveAllLight.length) {
            // have devs
            tmpRoom.roomStatus = Math.max.apply(null, saveAllLight)
        }
        list.push(tmpRoom)
        // 复位
        tmpRoom = { roomId: 0, roomName: '', roomMac: 0, roomStatus: 0, devList: [] }
    }
    app.globalData.homeList = list
    console.log("getHomeList - ok! ", app.globalData.homeList)
}

export async function firstGetHomeList() {
    await cloudLogin()
    await roomListGet()
    await updateRoomDevList(app.globalData.roomList)
}

export async function getHomeList() {
    if (app.globalData.payload == null) {
        await cloudLogin()
    } else {
        // 5 分钟获取一次 令牌
        if (new Date().getMinutes() - app.globalData.firstRunTime > 5) {
            app.globalData.firstRunTime = new Date().getMinutes()
            await cloudLogin()
        }
    }
    await roomListGet()
    await updateRoomDevList(app.globalData.roomList)
}

export async function changeStatus() {
    console.log("changeStatus")
    await getHomeList()
    app.globalData.refreshStatus = true
}

export async function roomControl(roomId, cw, brightness) {
    var list = app.globalData.homeList
    for (let i = 0; i < list.length; i++) {
        if (roomId == list[i].roomId) {
            if (cw == null && brightness != null) {
                for (let j = 0; j < list[i].devList.length; j++) {
                    await saveOrUpdateDevice(roomId, list[i].devList[j].devName, list[i].devList[j].devType, list[i].devList[j].devCW, brightness, list[i].devList[j].devId)
                }
            } else if (cw != null && brightness == null) {
                for (let j = 0; j < list[i].devList.length; j++) {
                    await saveOrUpdateDevice(roomId, list[i].devList[j].devName, list[i].devList[j].devType, cw, list[i].devList[j].devBrightness, list[i].devList[j].devId)
                }
            } else {
                for (let j = 0; j < list[i].devList.length; j++) {
                    await saveOrUpdateDevice(roomId, list[i].devList[j].devName, list[i].devList[j].devType, cw, brightness, list[i].devList[j].devId)
                }
            }
            // setTimeout(() => {
            changeStatus()
            // }, 100);
            return;
        }
    }
}

export async function devControl(devId, cw, brightness) {
    var list = app.globalData.homeList

    for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < list[i].devList.length; j++) {
            if (devId == list[i].devList[j].devId) {
                if (cw == null && brightness != null) {
                    await saveOrUpdateDevice(list[i].devList[j].roomId, list[i].devList[j].devName, list[i].devList[j].devType, list[i].devList[j].devCW, brightness, devId)
                } else if (cw != null && brightness == null) {
                    await saveOrUpdateDevice(list[i].devList[j].roomId, list[i].devList[j].devName, list[i].devList[j].devType, cw, list[i].devList[j].brightness, devId)
                } else {
                    await saveOrUpdateDevice(list[i].devList[j].roomId, list[i].devList[j].devName, list[i].devList[j].devType, cw, brightness, devId)
                }
                // setTimeout(() => {
                changeStatus()
                // }, 100);
                return;
            }
        }
    }
}